package com.zhuyi.broadcast.service;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Service
public class WebSocketService {

    // 存储所有 WebSocket 会话
    private final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    // 新用户连接时调用，WebSocket 会话加入集合
    public void addSession(WebSocketSession session) {
        sessions.add(session);
    }

    // 用户关闭连接时调用，WebSocket 会话从集合移除
    public void removeSession(WebSocketSession session) {
        sessions.remove(session);
    }

    // 处理消息，这里可以处理客户端发送的消息
    public void handleMessage(String message, WebSocketSession session) {
        // 可以在这里处理客户端发送的消息
        System.out.println("Received message: " + message);
    }

    // 向所有用户发送消息
    public void notifyAllUsers(String message) {
        for (WebSocketSession session : sessions) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new org.springframework.web.socket.TextMessage(message));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
